package com.sat.order.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sat.goods.feign.GoodsFeign;
import com.sat.order.dao.OrderItemMapper;
import com.sat.order.dao.OrderMapper;
import com.sat.order.pojo.OrderItem;
import com.sat.order.pojo.Order;
import com.sat.order.service.OrderService;
import com.sat.user.feign.AddressFeign;
import com.sat.user.pojo.Address;
import entity.IdWorker;
import entity.Result;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 如梦技术
 */

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private GoodsFeign goodsFeign;
    @Autowired
    private AddressFeign addressFeign;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /***
     * 订单的删除操作
     */
    @Override
    public void deleteOrder(String id) {
        //改状态   TODO 还有一些属性没封装完
        Order order = (Order) redisTemplate.boundHashOps("Order").get(id);
        order.setUpdateTime(new Date());
        order.setPayStatus("2");    //支付失败
        orderMapper.updateByPrimaryKeySelective(order);

        //TODO 回滚库存 需不需要回滚看具体业务逻辑
        //删除缓存
        //redisTemplate.boundHashOps("Order").delete(id);
    }

    /**
     * 订单修改
     * @param outtradeno    订单号
     * @param paytime   支付时间
     * @param transactionid    微信支付的交易流水号
     */
    @Override
    public void updateStatus(String outtradeno, String paytime, String transactionid) throws Exception{
        //1.修改订单
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMddHHmmss");
        Date parse = simpleDateFormat.parse(paytime);
        Order order = orderMapper.selectByPrimaryKey(outtradeno);
        order.setUpdateTime(new Date());    //时间也可以从微信接口返回过来，这里为了方便，我们就直接使用当前时间了
        order.setPayTime(parse);
        order.setTransactionId(transactionid);  //交易流水号
        order.setPayStatus("1");    //已支付
        orderMapper.updateByPrimaryKeySelective(order);
        //2.删除Redis中的订单记录
        //redisTemplate.boundHashOps("Order").delete(outtradeno);
    }

    /**
     * 添加订单和订单项
     * @param skuids
     * @param addressId
     * @return
     * http://127.0.0.1:9001/order/add?skuids=1148477873196113920&skuids=1148477873175142400&addressId=1
     * skuid需要购物车有该skuid
     */
    @Override
    public void add(Long[] skuids, Integer addressId, String username) {

        //获取用户购物车
        BoundHashOperations boundHashOperations = redisTemplate.boundHashOps("cart_" + username);
        //订单id
        Long orderId = idWorker.nextId();
        Integer totalNum = 0;
        Integer totalMoney = 0;
        for (Long skuid : skuids) {
            //校验库存  可能情况：下单的时候，商品库存足够下单成功了，不足的会失败。造成部分成功部分失败
            OrderItem orderItem = (OrderItem) boundHashOperations.get(skuid);
            orderItem.setOrderId(String.valueOf(orderId));
            orderItem.setId(String.valueOf(idWorker.nextId()));
            totalNum += orderItem.getNum();
            totalMoney += orderItem.getMoney();
            //不需要返回值也可，如果更新失败goodsFeign.updateSkuNum会抛出运行时异常
            Result<Integer> integerResult = goodsFeign.updateSkuNum(skuid, orderItem.getNum());

            //添加订单项
            orderItemMapper.insert(orderItem);
            //TODO  删除购物车
        }

        //添加订单    还有部分属性没封装完
        Result<Address> result = addressFeign.findAddress(addressId);
        Address address = result.getData();
        Order order = new Order();
        Date date = new Date();
        order.setId(String.valueOf(orderId));
        order.setTotalNum(totalNum);
        order.setTotalMoney(totalMoney);
        order.setCreateTime(date);
        order.setUpdateTime(date);
        order.setReceiverAddress(address.getAddress());
        order.setReceiverMobile(address.getPhone());
        order.setShippingName(address.getAlias());
        order.setUsername(address.getUsername());
        order.setReceiverContact(address.getContact());
        orderMapper.insert(order);


        rabbitTemplate.convertAndSend("add_order_exchange","sat.order.add",orderId.toString());

    }

    /**
     * Order条件+分页查询
     * @param order 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public PageInfo<Order> findPage(Order order, int page, int size){
        //分页
        PageHelper.startPage(page,size);
        //搜索条件构建
        Example example = createExample(order);
        //执行搜索
        return new PageInfo<Order>(orderMapper.selectByExample(example));
    }

    /**
     * Order分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageInfo<Order> findPage(int page, int size){
        //静态分页
        PageHelper.startPage(page,size);
        //分页查询
        return new PageInfo<Order>(orderMapper.selectAll());
    }

    /**
     * Order条件查询
     * @param order
     * @return
     */
    @Override
    public List<Order> findList(Order order){
        //构建查询条件
        Example example = createExample(order);
        //根据构建的条件查询数据
        return orderMapper.selectByExample(example);
    }


    /**
     * Order构建查询对象
     * @param order
     * @return
     */
    public Example createExample(Order order){
        Example example=new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if(order!=null){
            // 订单id
            if(!StringUtils.isEmpty(order.getId())){
                    criteria.andEqualTo("id",order.getId());
            }
            // 数量合计
            if(!StringUtils.isEmpty(order.getTotalNum())){
                    criteria.andEqualTo("totalNum",order.getTotalNum());
            }
            // 金额合计
            if(!StringUtils.isEmpty(order.getTotalMoney())){
                    criteria.andEqualTo("totalMoney",order.getTotalMoney());
            }
            // 优惠金额
            if(!StringUtils.isEmpty(order.getPreMoney())){
                    criteria.andEqualTo("preMoney",order.getPreMoney());
            }
            // 邮费
            if(!StringUtils.isEmpty(order.getPostFee())){
                    criteria.andEqualTo("postFee",order.getPostFee());
            }
            // 实付金额
            if(!StringUtils.isEmpty(order.getPayMoney())){
                    criteria.andEqualTo("payMoney",order.getPayMoney());
            }
            // 支付类型，1、在线支付、0 货到付款
            if(!StringUtils.isEmpty(order.getPayType())){
                    criteria.andEqualTo("payType",order.getPayType());
            }
            // 订单创建时间
            if(!StringUtils.isEmpty(order.getCreateTime())){
                    criteria.andEqualTo("createTime",order.getCreateTime());
            }
            // 订单更新时间
            if(!StringUtils.isEmpty(order.getUpdateTime())){
                    criteria.andEqualTo("updateTime",order.getUpdateTime());
            }
            // 付款时间
            if(!StringUtils.isEmpty(order.getPayTime())){
                    criteria.andEqualTo("payTime",order.getPayTime());
            }
            // 发货时间
            if(!StringUtils.isEmpty(order.getConsignTime())){
                    criteria.andEqualTo("consignTime",order.getConsignTime());
            }
            // 交易完成时间
            if(!StringUtils.isEmpty(order.getEndTime())){
                    criteria.andEqualTo("endTime",order.getEndTime());
            }
            // 交易关闭时间
            if(!StringUtils.isEmpty(order.getCloseTime())){
                    criteria.andEqualTo("closeTime",order.getCloseTime());
            }
            // 物流名称
            if(!StringUtils.isEmpty(order.getShippingName())){
                    criteria.andEqualTo("shippingName",order.getShippingName());
            }
            // 物流单号
            if(!StringUtils.isEmpty(order.getShippingCode())){
                    criteria.andEqualTo("shippingCode",order.getShippingCode());
            }
            // 用户名称
            if(!StringUtils.isEmpty(order.getUsername())){
                    criteria.andLike("username","%"+order.getUsername()+"%");
            }
            // 买家留言
            if(!StringUtils.isEmpty(order.getBuyerMessage())){
                    criteria.andEqualTo("buyerMessage",order.getBuyerMessage());
            }
            // 是否评价
            if(!StringUtils.isEmpty(order.getBuyerRate())){
                    criteria.andEqualTo("buyerRate",order.getBuyerRate());
            }
            // 收货人
            if(!StringUtils.isEmpty(order.getReceiverContact())){
                    criteria.andEqualTo("receiverContact",order.getReceiverContact());
            }
            // 收货人手机
            if(!StringUtils.isEmpty(order.getReceiverMobile())){
                    criteria.andEqualTo("receiverMobile",order.getReceiverMobile());
            }
            // 收货人地址
            if(!StringUtils.isEmpty(order.getReceiverAddress())){
                    criteria.andEqualTo("receiverAddress",order.getReceiverAddress());
            }
            // 订单来源：1:web，2：app，3：微信公众号，4：微信小程序  5 H5手机页面
            if(!StringUtils.isEmpty(order.getSourceType())){
                    criteria.andEqualTo("sourceType",order.getSourceType());
            }
            // 交易流水号
            if(!StringUtils.isEmpty(order.getTransactionId())){
                    criteria.andEqualTo("transactionId",order.getTransactionId());
            }
            // 订单状态,0:未完成,1:已完成，2：已退货
            if(!StringUtils.isEmpty(order.getOrderStatus())){
                    criteria.andEqualTo("orderStatus",order.getOrderStatus());
            }
            // 支付状态,0:未支付，1：已支付，2：支付失败
            if(!StringUtils.isEmpty(order.getPayStatus())){
                    criteria.andEqualTo("payStatus",order.getPayStatus());
            }
            // 发货状态,0:未发货，1：已发货，2：已收货
            if(!StringUtils.isEmpty(order.getConsignStatus())){
                    criteria.andEqualTo("consignStatus",order.getConsignStatus());
            }
            // 是否删除
            if(!StringUtils.isEmpty(order.getIsDelete())){
                    criteria.andEqualTo("isDelete",order.getIsDelete());
            }
        }
        return example;
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(String id){
        orderMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改Order
     * @param order
     */
    @Override
    public void update(Order order){
        orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     * 增加Order
     * @param order
     */
    @Override
    public void add(Order order){
        orderMapper.insert(order);
    }

    /**
     * 根据ID查询Order
     * @param id
     * @return
     */
    @Override
    public Order findById(String id){
        return  orderMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询Order全部数据
     * @return
     */
    @Override
    public List<Order> findAll() {
        return orderMapper.selectAll();
    }
}
